package com.xixilala.video.views

import android.app.Activity
import android.content.Context
import android.hardware.Camera
import android.util.AttributeSet
import android.view.SurfaceHolder
import android.view.SurfaceView
import com.xixilala.video.App
import com.xixilala.video.util.CameraUtil
import com.xixilala.video.util.LogUtil
import java.lang.Math.min

class CameraSurfaceView:SurfaceView, SurfaceHolder.Callback  {

    private lateinit var myHolder: SurfaceHolder
    private var camera: Camera? = null

    private var previewSizeList:List<Camera.Size>? = null

    private var dWidth=0
    private var dHeight=0

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        initial()
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        initCamera()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        camera?.release()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        if (previewSizeList != null) {
            //找到那个和view等宽或小于里最大的，并且高度最小的
            var sameScreen = false
            previewSizeList!!.forEach {
                if (it.width == measuredWidth && !sameScreen) {
                    sameScreen = true
                }
                if (sameScreen) {
                    dWidth = measuredWidth
                    if (dWidth == it.width) {
                        dHeight = if (dHeight == 0) {
                            it.height
                        } else {
                            min(it.height, dHeight)
                        }
                    }
                }
            }
            if (!sameScreen) {
                previewSizeList!!.forEach {
                    if (dWidth <= it.width) {
                        dWidth = it.width
                        dHeight = it.height
                    }
                }
            }
            LogUtil.d("desire width=$dWidth  height=$dHeight")


        }
    }

    private fun initCamera() {
        camera = Camera.open(0).apply {
            if (previewSizeList == null) {
                val parameters = parameters
                previewSizeList = parameters.supportedPreviewSizes
            }
        }
    }

    private fun initial() {
        holder.addCallback(this)
        myHolder = holder
    }

    override fun surfaceCreated(holder: SurfaceHolder) {

    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        camera?.run {

            parameters?.setPreviewSize(dWidth,dHeight)
            setDisplayOrientation(CameraUtil.calculateCameraPreviewOrientation(App.appContext, 0))
            setPreviewDisplay(myHolder)
            startPreview()
        }
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {

    }
}